package com.yswy.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.app.service.UserThirdPartyAccountService;
import com.yswy.domain.entity.UserThirdPartyAccount;
import com.yswy.domain.mapper.UserThirdPartyAccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class UserThirdPartyAccountServiceImpl extends ServiceImpl<UserThirdPartyAccountMapper, UserThirdPartyAccount>
        implements UserThirdPartyAccountService {

    @Override
    public List<UserThirdPartyAccount> accountFind(Integer accountType, Long userId) {
        return list(Wrappers.<UserThirdPartyAccount>lambdaQuery()
                .eq(UserThirdPartyAccount::getUserId, userId)
                .eq(null != accountType, UserThirdPartyAccount::getAccountType, accountType));
    }

    @Override
    public void bindZfb(String account, String realName, Long userId) {

        int count  = count(new LambdaQueryWrapper<UserThirdPartyAccount>().eq(UserThirdPartyAccount::getAccountName,realName)
                .eq(UserThirdPartyAccount::getAccountNum,account));
        if (count>0){
            throw new IllegalArgumentException("支付宝已被绑定,请先解绑或换个支付宝");
        }

        UserThirdPartyAccount bo = getOne(Wrappers.<UserThirdPartyAccount>lambdaQuery()
                .eq(UserThirdPartyAccount::getAccountType , 0)
                .eq(UserThirdPartyAccount::getUserId, userId));
        if (null == bo || null == bo.getId()) {
            save(UserThirdPartyAccount.builder()
                    .userId(userId)
                    .accountType(0)
                    .accountName(realName)
                    .accountNum(account)
                    .createTime(new Date())
                    .build());
        } else {
            bo.setAccountNum(account);
            bo.setAccountName(realName);
            bo.setUpdateTime(new Date());
            updateById(bo);
        }
    }

    @Override
    public void bindWx(String account, String realName, Long userId) {
        UserThirdPartyAccount bo = getOne(Wrappers.<UserThirdPartyAccount>lambdaQuery()
                .eq(UserThirdPartyAccount::getAccountType , 0)
                .eq(UserThirdPartyAccount::getUserId, userId));
        if (null == bo || null == bo.getId()) {
            save(UserThirdPartyAccount.builder()
                    .userId(userId)
                    .accountType(1)
                    .accountName(realName)
                    .accountNum(account)
                    .createTime(new Date())
                    .build());
        } else {
            bo.setAccountNum(account);
            bo.setAccountName(realName);
            bo.setUpdateTime(new Date());
            updateById(bo);
        }

    }


}
